package com.hngy.xpq.android_practice.ui.home;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.hngy.xpq.android_practice.R;
import com.hngy.xpq.android_practice.adapter.CommAdapter;
import com.hngy.xpq.android_practice.assets.XpqIcoMoon;
import com.hngy.xpq.android_practice.assets.XpqIcoMoonUtils;
import com.hngy.xpq.android_practice.bean.Comm;
import com.hngy.xpq.android_practice.bean.Recording;
import com.hngy.xpq.android_practice.database.SQLiteComm;
import com.hngy.xpq.android_practice.database.SQLiteRecording;
import com.hngy.xpq.android_practice.rewrite.RewriteListView;

import java.util.List;

public class HomeFragment extends Fragment {

    private int[] ima = new int[]{R.drawable.comm_one,R.drawable.comm_two,R.drawable.coom_three,R.drawable.coom_fove};
    private Animation[] animations = new Animation[2];
    final int FLAG = 0x001;
    private ViewFlipper comm;
    private Message message;
    TextView search;
    Button comm_search;
    RewriteListView home_grid;
    SharedPreferences merchant,comms,main;
    SQLiteComm sqLiteComm;
    SQLiteRecording sqLiteRecording;
    List<Comm> list;
    List<Recording> recordings;
    Recording r;
    CommAdapter adapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        search = root.findViewById(R.id.search);
        comm = root.findViewById(R.id.comm_flipper);
        comm_search = root.findViewById(R.id.comm_search);
        home_grid = root.findViewById(R.id.home_list);

        comm_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),SearchComm.class);
                startActivity(intent);
            }
        });

        IcoMoonUtil();
        CommFlipper();
        HomeGrid();
        return root;
    }

    //通过全局查询、随机进行商品推送，第一次通过id注册排序显示数据，第二次根据浏览、爱好显示数据
    private void HomeGrid() {
        merchant = getActivity().getSharedPreferences("merchant", Context.MODE_PRIVATE);
        main = getActivity().getSharedPreferences("main",Context.MODE_PRIVATE);
        HomeData();
        comms = getActivity().getSharedPreferences("comm",Context.MODE_PRIVATE);
        home_grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(),User_Comm.class);
                Comm c = list.get(position);
                SharedPreferences.Editor editor = comms.edit();
                editor.putString("name",c.getMerchant_name());
                editor.putString("price",c.getComm_price());
                editor.putString("phone",c.getComm_phone());
                editor.putString("comm_name",c.getComm_name());
                editor.putString("position", String.valueOf(position));
                editor.putString("math","");
                editor.putString("status",c.getStatus());
                editor.putString("ndx","1");
                editor.commit();
                SharedPreferences.Editor editor1 = merchant.edit();
                editor1.putString("name",c.getMerchant_name());
                editor1.commit();
                //浏览查重
                if (recordings != null){
                    recordings.clear();
                }
                recordings = sqLiteRecording.recordingQuery(main.getString("name",""));
                int index = 0;
                for (int x = 0 ; x < recordings.size() ; x++ ){
                    if (recordings.get(x).getRecording_name().equals(c.getComm_name())){
                        index = 1;
                    }
                }
                //添加浏览记录
                if ( index == 0 ){
                    r = new Recording();
                    r.setMerchant_name(c.getMerchant_name());
                    r.setRecording_name(c.getComm_name());
                    r.setUser_name(main.getString("name",""));
                    r.setLikes("recording");
                    if (sqLiteRecording.recording_add(r)){
                        Log.i("保存成功","");
                    } else {
                        Log.i("保存失败","");
                    }
                }
                startActivity(intent);
            }
        });
    }

    //数据通过适配器展示
    private void HomeData() {
        sqLiteComm = new SQLiteComm(getActivity());
        sqLiteRecording = new SQLiteRecording(getActivity());
        if (list != null){
            list.clear();
        }
        //获得所有商品信息
        list = sqLiteComm.CommSearch("");
        //适配器的数据安置
        adapter = new CommAdapter(getActivity(),list);
        home_grid.setAdapter(adapter);
        //将界面拖上去
        home_grid.setFocusable(false);
    }

    private void CommFlipper() {   //广告瀑布
        for (int i = 0 ; i < ima.length ; i++){
            ImageView imageView = new ImageView(getActivity());
            imageView.setImageResource(ima[i]);
            comm.addView(imageView);
        }
        animations[0] = AnimationUtils.loadAnimation(getActivity(),R.anim.slide_in_right);
        animations[1] = AnimationUtils.loadAnimation(getActivity(),R.anim.slide_out_left);
        comm.setInAnimation(animations[0]);     //广告进入画面
        comm.setOutAnimation(animations[1]);    //广告退出画面

        message = Message.obtain();     //获得对象
        message.what = FLAG;            //设置消息代码
        handler.sendMessage(message);   //发送
    }

    private void IcoMoonUtil() {   //映射搜索框图片文字
        search.setText(XpqIcoMoon.COMM);
        XpqIcoMoonUtils.setIOC(search);
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == FLAG){
                comm.showPrevious();
            }
            message = handler.obtainMessage(FLAG);
            handler.sendMessageDelayed(message,3000);    //设置3秒延迟
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==2){
            HomeData();
        }
    }
}